package anbook.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import anbook.dao.controller.MemberController;
import anbook.dto.Member;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.sendRedirect("/BookProject/");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf8"); 
		
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		
		out.println("<meta charset=utf-8>");
		if (email == null || password == null){
			out.println("<script>");
			out.println("alert('이메일 또는 패스워드를 입력해주세요..');");
			out.println("history.back(-1);");
			out.println("</script>");
			return;
		}
		
		MemberController mc = new MemberController();
		Member member = new Member(email,password);
		
		boolean ret = mc.login(member);
		
		out.println("<script>");
		if (ret){
			session.setAttribute("email", email);
			out.println("location.href = '/BookProject/aMain.jsp';");
		}else {
			out.println("alert('이메일 또는 패스워드가 틀렸습니다..');");
			out.println("history.back(-1);");
		}
		out.println("</script>");
	}

}
